package com.qf.zhouce0630.controller;

import com.qf.zhouce0630.esvo.VoteInfo;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author UNIQ7xi
 * @Date 2023/6/30 19:21
 * @Version v1.8
 **/
@RestController
@RequestMapping("/vote")
public class VoteController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    @PostMapping("/pick")
    public String vote(@RequestBody VoteInfo voteInfo){
        rabbitTemplate.convertAndSend("vote-exchange","",voteInfo);
        return "投票成功!";

    }

    @RabbitListener(queues = "vote-es-queue")
    public void receiveVoteInfo(VoteInfo voteInfo){
        IndexQuery indexQuery = new IndexQueryBuilder()
                .withIndexName("vote-liushui-index")
                .withType("vote-liushui-type")
                .withObject(voteInfo)
                .build();

        elasticsearchOperations.index(indexQuery);
    }
}
